import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from "axios";
import { Api } from "./api";
import { router } from "@/routes";
import { Message } from "@arco-design/web-vue";
import { getToken, getRefreshToken, removeToken, setTokenPair } from "@/utils/token";
import { localStorage } from "@/utils/storage";

const baseURL='http://localhost:3000';
export const api = new Api({
    baseURL: baseURL,
})
api.instance.interceptors.request.use((config:InternalAxiosRequestConfig) => {
	let token=getToken()
	if(token){
		config.headers.Authorization = `Bearer ${token}`
	}
    return config;
})
// 后台刷新token的标志，防止重复刷新
let isRefreshing = false;
let failedQueue: Array<{resolve: Function, reject: Function}> = [];

// 处理队列中的请求
const processQueue = (error: any, token: string | null = null) => {
    failedQueue.forEach(({ resolve, reject }) => {
        if (error) {
            reject(error);
        } else {
            resolve(token);
        }
    });
    failedQueue = [];
};

// 后台刷新token
const refreshTokenInBackground = async (): Promise<void> => {
    try {
        const refreshToken = getRefreshToken();
        if (!refreshToken) {
            throw new Error('No refresh token available');
        }

        const response = await axios.post(`${baseURL}/auth/refresh`, {
            refresh_token: refreshToken
        });

        const { access_token, refresh_token: new_refresh_token } = response.data;

        // 保存新的token对（保持原有的存储方式）
        const isRemembered = !!localStorage.get('access_token');
        setTokenPair(access_token, new_refresh_token, isRemembered);

        console.log('Token refreshed successfully in background');
    } catch (error) {
        console.error('Background token refresh failed:', error);
        // 静默失败，不影响用户体验
    }
};

api.instance.interceptors.response.use((res:AxiosResponse) => {
    // 检查token状态 - 被动监控模式
    const expiresIn = parseInt(res.headers['x-token-expires-in'] || '0');
    const expiringSoon = res.headers['x-token-expiring-soon'] === 'true';

    // 如果token即将过期（5分钟内），主动刷新
    if (expiringSoon && expiresIn > 0) {
        refreshTokenInBackground();
    }

    // 检查是否有新的token（主动刷新的结果）
    if (res.headers['x-token-refreshed'] === 'true') {
        const newAccessToken = res.headers['x-new-access-token'];
        const newRefreshToken = res.headers['x-new-refresh-token'];

        if (newAccessToken && newRefreshToken) {
            const isRemembered = !!localStorage.get('access_token');
            setTokenPair(newAccessToken, newRefreshToken, isRemembered);
            console.log('Token refreshed from response headers');
        }
    }

    return Promise.resolve(res)
}, async (err:AxiosError) => {
    const originalRequest = err.config as any;

    if(err.response?.status === 401 && !originalRequest._retry){
        if (isRefreshing) {
            // 如果正在刷新token，将请求加入队列
            return new Promise((resolve, reject) => {
                failedQueue.push({ resolve, reject });
            }).then(token => {
                if (originalRequest) {
                    originalRequest.headers.Authorization = `Bearer ${token}`;
                    return api.instance(originalRequest);
                }
            }).catch(err => {
                return Promise.reject(err);
            });
        }

        originalRequest._retry = true;
        isRefreshing = true;

        try {
            const refreshToken = getRefreshToken();
            if (!refreshToken) {
                throw new Error('No refresh token available');
            }

            const response = await axios.post(`${baseURL}/auth/refresh`, {
                refresh_token: refreshToken
            });

            const { access_token, refresh_token: new_refresh_token } = response.data;

            // 保存新的token对
            const isRemembered = !!localStorage.get('access_token');
            setTokenPair(access_token, new_refresh_token, isRemembered);

            // 更新原始请求的token
            if (originalRequest) {
                originalRequest.headers.Authorization = `Bearer ${access_token}`;
            }

            // 处理队列中的请求
            processQueue(null, access_token);

            // 重新发送原始请求
            return api.instance(originalRequest);

        } catch (refreshError) {
            // 刷新失败，清除token并跳转登录
            processQueue(refreshError, null);
            Message.error('登录已过期，请重新登录');
            removeToken();
            router.replace('/login');
            return Promise.reject(refreshError);
        } finally {
            isRefreshing = false;
        }
    } else {
        // 其他错误
        //@ts-ignore
        Message.error(err.response?.data?.message || '请求失败');
    }

    return Promise.reject(err.response);
})
